package  com.http.get;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by lanouhn on 17/7/18.
 */
public class HttpPicture {
    private static final URL URL_PATH = null;
    String UPL_PATH = "http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=hello%20kitty&hs=2&pn=2&spn=0&di=34575928750&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&ie=utf-8&oe=utf-8&cl=2&lm=-1&cs=1127573813%2C2404286861&os=2421143484%2C2025387998&simid=3347623622%2C256159157&adpicid=0&lpn=0&ln=30&fr=ala&fm=&sme=&cg=&bdtype=0&oriquery=hello%20kitty&objurl=http%3A%2F%2Fp9.qhimg.com%2Ft019ae6b305f78b5455.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fkwthj_z%26e3Bf5_z%26e3Bv54AzdH3F15vAzdH3Fitfp56yAzdH3Ft1AzdH3Fdmmdbc&gsm=0\n";

    public static void saveImageToDisk(){
        InputStream inputStream = getInputStream();
        byte[]data = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try{
            fileOutputStream = new FileOutputStream("/Users/lanouhn/Desktop/t019ae6b305f78b5455.jpg");
            while ((len = InputStream.read(data))!=-1){
                fileOutputStream.write(data,0,len);
            }

        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(fileOutputStream != null){
                try{
                    fileOutputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static InputStream getInputStream(){
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try{
            URL url = new URL(URL_PATH);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode == 200){
                inputStream = httpURLConnection.getInputStream();
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        return inputStream;
    }

    public static void main(String[]args){
        saveImageToDisk();
    }
}
